/* eslint-disable react/jsx-indent */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import Link from 'umi/link';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Select, Button, message, Modal, Tooltip, Divider, Spin } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import TextOverFlow from '../../components/TextOverFlow';
import styles from '../../../utils/utils.less';
import BatchTaskProgress from '../../components/BatchTaskProgress';
import AssociationTable from './AssociationTable';

const FormItem = Form.Item;
const { Option } = Select;
// let interval = null;

@connect(({ addempsend, loading, protocol }) => ({
  dataInfo: protocol.detail || {},
  addempsend,
  productList: protocol.addOrEdit.productList,
  loading: loading.models.addempsend,
  dataList: addempsend.dataList,
  placeExecutionList: addempsend.placeExecutionList,
  formFieldsValue: addempsend.formFieldsValue,
  selectRowKeys: addempsend.selectRowKeys,
  selectRows: addempsend.selectRows,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      areaIdList: [],
      supperId: '',
      tableLoading: false,
      supplyLoading: false, // 下拉loading
    };
    this.tableSearchLayout = {
      labelCol: { md: { span: 5 } },
      wrapperCol: { md: { span: 17 } },
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'publicdata/fetchSupplyList',
      payload: { name: null, state: 2 },
    });
    this.getList(1, 10);
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'addempsend/updateModelData',
      payload: { progressPercent: 0 },
    });
  }

  getList = (currentPage = 1, pageSize = 10) => {
    const { dispatch, formFieldsValue, selectRowKeys, form } = this.props;
    form.resetFields();
    const pageArg = { currentPage, pageSize };
    this.setState({
      tableLoading: true,
    });
    dispatch({
      type: 'addempsend/updateModelData',
      payload: { batchId: '', progressPercent: 0 },
    });
    dispatch({
      type: 'addempsend/samllGua',
      payload: {
        pageArg,
        ...formFieldsValue,
        cityId: formFieldsValue?.cityId?.key,
        sendAddTaskIds: (selectRowKeys.length && selectRowKeys) || null,
      },
    }).then(res => {
      if (res.success) {
        this.setState({
          tableLoading: false,
        });
      } else {
        this.setState({
          tableLoading: false,
        });
      }
    });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { dispatch } = this.props;
    this.setState({
      tableLoading: true,
    });
    dispatch({
      type: 'addempsend/tableChange',
      payload: {},
    });

    this.getList(pagination.current, pagination.pageSize);
  };

  // 选择供应商带出供应商协议
  supplierLists = (value, record, index) => {
    const {
      dispatch,
      form,
      dataList,
      dataList: { pagination },
    } = this.props;
    this.setState({
      supplyLoading: true,
    });
    const params = {
      areaId: record.cityId && record.cityId[0],
    };
    if (record.accuGrpIds) {
      const accuGrpstring = record.accuGrpIds.join(',');
      params.accuLsPkgId = accuGrpstring || null;
    }
    if (record.insGrpIds) {
      const insLsPkgIdstring = record.insGrpIds.join(',');
      params.insLsPkgId = insLsPkgIdstring || null;
    }
    const newIndex = (pagination.current - 1) * 10 + index;
    dataList.list[newIndex].supplierNameList = [];
    dispatch({
      type: 'addempsend/updateModelData',
      payload: { dataList },
    });

    dispatch({
      type: 'addempsend/supplierList',
      payload: { params, suppInfo: { value, record, index: newIndex } },
    }).then(res => {
      if (res.success) {
        if (res.data === []) {
          form.resetFields([`supply${newIndex}`]);
        }
      }
      this.setState({
        tableLoading: false,
        supplyLoading: false,
      });
    });
  };

  // 供应商调出供应商协议
  supplierAgreement = (e, record, idx, isSupp) => {
    this.setState({
      supplyLoading: true,
    });
    const {
      form,
      dataList,
      dispatch,
      dataList: { pagination },
    } = this.props;
    const newIndex = (pagination.current - 1) * 10 + idx;
    const supindex = `supplier${newIndex}`;
    // 1是供应商清空供应商协议
    if (isSupp === 1) {
      form.resetFields([supindex]);
      form.resetFields([`supplier${newIndex}`]);
    }
    dataList.list[newIndex].supplyDatalist = [];
    dispatch({
      type: 'addempsend/updateModelData',
      payload: { dataList },
    });
    const areaIdList = [];
    const pdIdList = [];
    record.cityId.forEach(item => {
      areaIdList.push({
        areaId: item,
      });
    });
    record.pdId.forEach(item => {
      pdIdList.push({
        pdId: item,
      });
    });
    const params = {
      recvSuppId: e,
      serialNum: newIndex,
      areaList: areaIdList,
      detList: pdIdList,
      custId: record.custId,
      isSupp,
    };
    dispatch({
      type: 'addempsend/getAgreementList',
      payload: params,
    }).then(() => {
      this.setState({
        supplyLoading: false,
      });
    });
  };

  supplieragree = e => {
    const { dispatch } = this.props;
    const pagerArg = { currentPage: 1, pageSizes: 10 };
    const values = {
      pagerArg,
      suppProtName: e,
    };
    dispatch({
      type: 'addempsend/fetchAgreementList',
      payload: values,
    });
  };

  agreementList = (e, index) => {
    const {
      dispatch,
      dataList,
      dataList: { pagination },
    } = this.props;
    const newIndex = (pagination.current - 1) * 10 + index;
    dataList.list[newIndex].suppProtId = e;
    dispatch({
      type: 'addempsend/updateModelData',
      payload: { dataList },
    });
  };

  // 客户合同名称下拉模糊查询
  getData = (value, id) => {
    const { form } = this.props;
    if (id) {
      form.setFieldsValue({ [id]: value });
      this.setState({ [id]: value });
    }
  };

  // 发单
  invoice = (key, record) => {
    const { dispatch } = this.props;
    // key 1 是保存关系并发单，2 是仅发单
    const paramMessgae = {
      custId: record.custId,
      cityId: record.cityId && record.cityId[0],
      recvSuppId: record.suppId,
    };
    const paramet = {
      custId: record.custId,
      cityId: record.cityId && record.cityId[0],
      pdId: record.pdId,
      suppProtId: record.suppProtId,
      sendAddTaskIds: record.sendOrdAddTaskIds || null,
    };
    if (!record.suppProtId) {
      message.warning('请选择供应商协议！');
      return;
    }
    if (!record.suppId) {
      message.warning('请选择供应商！');
      return;
    }
    if (key === 1) {
      if (
        (record.defaultValueSupp &&
          record.defaultValueSupp[0] &&
          record.defaultValueSupp[0].suppId !== record.suppId) ||
        (record.defaultValueSuppProt &&
          record.defaultValueSuppProt[0] &&
          record.defaultValueSuppProt[0].suppProtId !== record.suppProtId)
      ) {
        Modal.confirm({
          icon: <ExclamationCircleOutlined />,
          title: '温馨提示',
          content: `此客户之前关联的是 ${record.defaultValueSupp[0].name} 供应商和 ${
            record.defaultValueSuppProt[0].suppProtName
          } 协议，如果只是特殊情况使用此供应商或协议，可选择仅发单；`,
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            this.setState({
              tableLoading: true,
            });
            dispatch({
              type: 'addempsend/sendAddper',
              payload: paramMessgae,
              callback: res => {
                if (res.data.flag) {
                  this.setState({
                    tableLoading: false,
                  });
                  const content = res.data.message;
                  Modal.confirm({
                    title: '温馨提示',
                    content,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                      dispatch({
                        type: 'addempsend/uploadFileWithProgress',
                        payload: {
                          params: paramet,
                          isSendType: key,
                        },
                      }).then(() => {
                        this.setState({
                          tableLoading: false,
                        });
                      });
                    },
                  });
                } else {
                  this.setState({
                    tableLoading: true,
                  });
                  dispatch({
                    type: 'addempsend/uploadFileWithProgress',
                    payload: {
                      params: paramet,
                      isSendType: key,
                    },
                  }).then(() => {
                    this.setState({
                      tableLoading: false,
                    });
                  });
                }
              },
            });
          },
        });
      } else {
        this.setState({
          tableLoading: true,
        });
        dispatch({
          type: 'addempsend/sendAddper',
          payload: paramMessgae,
          callback: res => {
            this.setState({
              tableLoading: false,
            });
            if (res.data.flag) {
              const content = res.data.message;
              Modal.confirm({
                title: '温馨提示',
                content,
                okText: '确定',
                cancelText: '取消',
                onOk: () => {
                  dispatch({
                    type: 'addempsend/uploadFileWithProgress',
                    payload: {
                      params: paramet,
                      isSendType: key,
                    },
                  }).then(() => {
                    this.setState({
                      tableLoading: false,
                    });
                  });
                },
              });
            } else {
              this.setState({
                tableLoading: true,
              });
              dispatch({
                type: 'addempsend/uploadFileWithProgress',
                payload: {
                  params: paramet,
                  isSendType: key,
                },
              }).then(() => {
                this.setState({
                  tableLoading: false,
                });
              });
            }
          },
        });
      }
    } else {
      const parametData = {
        suppProtId: record.suppProtId || '',
        recvSuppId: record.suppId || '',
        sendOrdAddTaskIds: record.sendOrdAddTaskIds || [],
      };
      this.setState({
        tableLoading: true,
      });
      dispatch({
        type: 'addempsend/uploadFileWithProgress',
        payload: {
          params: parametData,
          isSendType: key,
        },
      }).then(() => {
        this.setState({
          tableLoading: false,
        });
      });
    }
  };

  // 进度弹框显隐
  handleProgressModalVisible = flag => {
    const {
      dataList: { pagination },
      dispatch,
    } = this.props;
    if (!flag) {
      dispatch({
        type: 'addempsend/updateModelData',
        payload: {
          showProgress: false,
        },
      });
      const selectedLen = 1;
      if (
        pagination.current > 1 &&
        (pagination.total % pagination.pageSize === Number(selectedLen) ||
          Number(pagination.pageSize) === Number(selectedLen))
      ) {
        this.getList(pagination.current - 1, pagination.pageSize);
      } else {
        this.getList(pagination.current, pagination.pageSize);
      }
    }
  };

  // 查看当前有无任务
  checkHasTask = () => {
    const { dispatch } = this.props;
    // 查看当前有无任务进行
    dispatch({
      type: 'addempsend/checkHasTask',
    });
  };

  // 选择供应商
  modalAgreement = e => {
    this.setState({
      supperId: e,
    });
    const { dispatch, placeExecutionList } = this.props;
    const cityLists = [];
    placeExecutionList.forEach(item => {
      cityLists.push(item.key);
    });
    dispatch({
      type: 'addempsend/fetchProductList',
      payload: { suppId: e, areaIdList: cityLists },
    });
  };

  // 获取地区
  getAreaList = value => {
    const { dispatch } = this.props;
    const { supperId } = this.state;
    const cityLists = [];
    value.forEach(item => {
      cityLists.push(item.key);
    });

    dispatch({
      type: 'addempsend/addRegion',
      payload: value,
    });
    dispatch({
      type: 'addempsend/fetchProductList',
      payload: { suppId: supperId, areaIdList: cityLists },
    });
  };

  // 获取供应商名称
  getSuppName = value => {
    const { areaIdList } = this.state;
    if (areaIdList.length) {
      this.getProductList(value, areaIdList);
    }
  };

  // 获取产品下拉数据
  getProductList = (suppId, areaIdList) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'protocol/fetchProductList',
      payload: { suppId, areaIdList },
    });
  };

  render() {
    const { tableLoading, supplyLoading } = this.state;
    const {
      addempsend,
      dataList,
      form: { getFieldDecorator },
    } = this.props;
    const columns = [
      {
        title: '客户名称',
        dataIndex: 'cust',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'left', width: 140 } }),
        onCell: () => ({ style: { textAlign: 'left', width: 140 } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '执行地',
        dataIndex: 'city',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'left', width: 140 } }),
        onCell: () => ({ style: { textAlign: 'left', width: 140 } }),
        render: text => text || '--',
      },
      {
        title: '服务产品',
        dataIndex: 'pd',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'left' } }),
        onCell: () => ({ style: { textAlign: 'left' } }),
        render: text => <TextOverFlow text={text} />,
      },

      {
        title: (
          <Tooltip
            placement="top"
            title="供应商业务范围中产品、执行地以及社保公积金组合需要包含客户业务情况才能选到供应商"
          >
            <span>供应商</span>
            <ExclamationCircleOutlined style={{ marginLeft: 5 }} />
          </Tooltip>
        ),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'left' } }),
        onCell: () => ({ style: { textAlign: 'left' } }),
        dataIndex: 'suppId',
        render: (text, record, index) => (
          <FormItem style={{ margin: 0 }} className={styles.errorMsgRight}>
            {getFieldDecorator(`supply${index}`, {
              initialValue: (record.suppId && record.suppId) || undefined,
            })(
              <Select
                placeholder="请输入关键字检索"
                showSearch
                optionFilterProp="children"
                notFoundContent={supplyLoading ? <Spin size="small" /> : '暂无数据'}
                onChange={value => this.supplierAgreement(value, record, index, 1)}
                onFocus={value => this.supplierLists(value, record, index)}
                showArrow={false}
                style={{ width: 200 }}
              >
                {record.supplierNameList ? (
                  record.supplierNameList.map(item => (
                    <Option key={item.suppId} title={item.name}>
                      {item.name}
                    </Option>
                  ))
                ) : (
                  <Option />
                )}
              </Select>
            )}
          </FormItem>
        ),
      },

      {
        title: (
          <Tooltip
            placement="top"
            title="供应商协议中产品以及执行地需要包含客户业务情况才能选到供应商协议"
          >
            <span>供应商协议</span>
            <ExclamationCircleOutlined style={{ marginLeft: 5 }} />
          </Tooltip>
        ),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'left' } }),
        onCell: () => ({ style: { textAlign: 'left' } }),
        render: (text, record, index) => (
          <FormItem style={{ margin: 0 }} className={styles.errorMsgRight}>
            {getFieldDecorator(`supplier${index}`, {
              initialValue: (record.suppProtId && record.suppProtId) || undefined,
            })(
              <Select
                placeholder="请选择"
                onFocus={() => this.supplierAgreement(record.suppId, record, index, 2)}
                onSelect={e => this.agreementList(e, index)}
                notFoundContent={supplyLoading ? <Spin size="small" /> : '暂无数据'}
                showSearch
                optionFilterProp="children"
                style={{ width: 200 }}
              >
                {record.supplyDatalist
                  ? record.supplyDatalist.map(items => (
                      <Option key={items.suppProtId} title={items.suppProtName}>
                        {items.suppProtName}
                      </Option>
                    ))
                  : null}
              </Select>
            )}
          </FormItem>
        ),
      },

      {
        title: (
          <Tooltip
            placement="top"
            title={
              <div>
                <p>保存关系并发单：保存客户与协议关系，再有相同业务情况自动关联发单</p>
                <p>仅发单：单独指定供应商和协议，再有相同业务情况不会自动关联发单</p>
              </div>
            }
          >
            <span>操作</span>
            <ExclamationCircleOutlined style={{ marginLeft: 5 }} />
          </Tooltip>
        ),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'left', width: 200 } }),
        onCell: () => ({ style: { textAlign: 'left', width: 200 } }),
        render: (text, record, index) => (
          <div>
            <a onClick={() => this.invoice(1, record, index)}>保存关系并发单</a>
            <Divider type="vertical" />
            <a onClick={() => this.invoice(2, record, index)}>仅发单</a>
          </div>
        ),
      },
    ];
    return (
      <PageHeaderWrapper>
        <Card
          title="关联协议并发单"
          style={{ border: '0px', marginBottom: 24, fontSize: 16, color: '#262626' }}
        >
          <Form>
            {/* <StandardTable
              style={{ width: '100%' }}
              selectedRows={sleectedList}
              selectedRowKeys={selectedRowKeys}
              loading={tableLoading}
              data={dataList}
              rowKey={(record, index) => index}
              columns={columns}
              onSelectRow={false}
              rowSelection={false}
              onChange={this.handleStandardTableChange}
            /> */}
            <AssociationTable
              businessData={dataList.list}
              // rowKey={record => record.cust}
              tableLoading={tableLoading}
              columns={columns}
            />
          </Form>
        </Card>
        <BatchTaskProgress
          progressVisible={addempsend.showProgress}
          progressPercent={addempsend.progressPercent || 0}
          isShowResult={addempsend.progressPercent === 100}
          resultInfo={addempsend.resultInfo}
          checkHasTask={this.checkHasTask}
          handleProgressModalVisible={this.handleProgressModalVisible}
          maskClosable={false}
        />
        <FooterToolbar style={{ width: '100%' }}>
          <Link to="/sendordermanage/addemployee/index">
            <Button style={{ marginRight: 10 }}>返回</Button>
          </Link>
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
